package com.yami.shop.sys.multishop.controller;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yami.shop.common.annotation.SysLog;
import com.yami.shop.common.bean.SysConfig;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.service.SysConfigService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;


/**
 * 系统配置信息
 * @author lgh
 */
@Tag(name = "系统配置信息")
@ConditionalOnProperty(prefix = "yami", name = "expose.permission", havingValue = "true", matchIfMissing = true)
@RestController
@RequestMapping("/sys/config")
public class SysConfigController {
    @Autowired
    private SysConfigService sysConfigService;

    @GetMapping("/info/{key}")
    @Operation(summary =  "配置信息", description = "配置信息")
    @Parameter(name = "id", description = "配置id")
    public ServerResponseEntity<String> info(@PathVariable("key") String key){
        String value = sysConfigService.getValue(key);
        return ServerResponseEntity.success(value);
    }

    @SysLog("修改配置")
    @PostMapping("/update")
    @Operation(summary =  "修改配置", description = "修改配置")
    public ServerResponseEntity<Void> update(@RequestBody @Valid SysConfig config){

        SysConfig dbSysConfig = sysConfigService.getOne(new LambdaQueryWrapper<SysConfig>()
                .eq(SysConfig::getParamKey, config.getParamKey()));

        if (dbSysConfig != null && !Objects.equals(dbSysConfig.getParamKey(),config.getParamKey())) {
            // 系统已存在相同配置的key
            throw new YamiShopBindException("yami.same.key");
        }

        sysConfigService.updateValueByKey(config.getParamKey(), config.getParamValue());
        return ServerResponseEntity.success();
    }

}
